package com.qinyi.framework.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.qinyi.common.enums.DataSourceType;
import com.qinyi.framework.config.properties.DruidProperties;
import com.qinyi.framework.datasource.DynamicDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author wangan on 2019/5/31
 * @description
 */
@Configuration
public class DruidConfig {

	@Bean
	@ConfigurationProperties("spring.datasource.druid.master")
	public DataSource masterDataSource(DruidProperties druidProperties) {
		DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
		return druidProperties.creaateDataSource(dataSource);
	}

	@Bean
	@ConfigurationProperties("spring.datasource.druid.slave")
	@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
	public DataSource slaveDataSource(DruidProperties druidPropertie) {
		DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
		return druidPropertie.creaateDataSource(dataSource);
	}

	@Bean
	public DataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
		HashMap<Object, Object> datasourceMap = new HashMap<>();
		datasourceMap.put(DataSourceType.MASTER.name(), masterDataSource);
		datasourceMap.put(DataSourceType.SLAVE.name(), slaveDataSource);
		return new DynamicDataSource(masterDataSource, datasourceMap);
	}

}
